import * as aes from './lgaes.js';

let baseUrl = 'http://192.168.2.66:11042/api/v3.0';

// 不带token请求
const httpRequest = (opts, data) => {

	uni.onNetworkStatusChange(function(res) {
		if (!res.isConnected) {
			uni.showToast({
				title: '网络连接不可用！',
				icon: 'none'
			});
		}
		return false
	});
	let httpDefaultOpts = {
		url: baseUrl + opts.url,
		data: data,
		method: opts.method,
		header: opts.method == 'get' ? {
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		} : {
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/json; charset=UTF-8'
		},
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				resolve(res[1])
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
};

//带Token请求
const httpTokenRequest = (opts) => {
	uni.showLoading({
		title: '请求加载进行中...'
	});
	uni.onNetworkStatusChange(function(res) {
		if (!res.isConnected) {
			uni.showToast({
				title: '网络连接不可用！',
				icon: 'none'
			});
		}
		return false
	});
	const phone = "mobile"
	const userInfo = uni.getStorageSync("userInfo")
	const company = uni.getStorageSync('companny')
	const comId = company ? company.split("@")[1] : "";
	let token = userInfo.token
	if (!opts.url.endsWith("login")) {
		const a = hadToken(token)
		if (!a) {
			return false
		}
	}
	if (opts.data) {
		// json
		const temp = {
			...opts.data,
			uid: userInfo.id,
			companyId: comId,
		}
		const paramInfo = handleDeleteBlankParam(temp);
		const paramsBody = {
			bodyParams: aes.encrypt(JSON.stringify(paramInfo)),
		};
		opts.data = JSON.stringify(paramsBody);


	}

	let httpDefaultOpts = {
		url: baseUrl + opts.url,
		data: opts.data || {},
		method: opts.method,
		// header: opts.method == 'get' ? {
		// 	'X-Access-Token': token,
		// 	'X-Requested-With': 'XMLHttpRequest',
		// 	"Accept": "application/json",
		// 	"Content-Type": "application/json; charset=UTF-8"
		// } : {

		// 	'Content-Type': 'application/json; charset=UTF-8'
		// },
		// dataType: 'json',
	}
	if (!opts.url.endsWith("login")) {
		httpDefaultOpts.header = {
			Accept: 'application/json',
			'Content-Type': 'application/json; charset=utf-8',
			Authorization: token,
			'use-agent': phone,
		}
	} else {
		httpDefaultOpts.header = {
			Accept: 'application/json',
			'Content-Type': 'application/json; charset=utf-8',
			'use-agent': phone,
		}
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request({
			...httpDefaultOpts,
			success(res1) {
				const res = res1.data
				if (res && !res.meta) {
					return uni.showToast({
						title: '请求失败了' + res.message,
						icon: 'none',
						duration: 5000
					})
					reject(res)
				}
				if (res.meta.status == '000000') {
					const temp = {
						...res,
						data: {
							alert_msg: res.data.alert_msg,
							list: res.data.list && res.data.list.length > 0 ? JSON.parse(aes
								.decrypt(res.data
									.list)) : res.data.list,
							pagination: res.data.pagination,
							total: res.data.total,
						}
					};
					return resolve(temp)
				} else {
					uni.showToast({
						title: '请求出问题了' + res.data.alert_msg,
						icon: 'none',
						duration: 5000,
						complete: function() {
							if (res.data.alert_msg.indexOf('token') > -1) {
								reject(res)
								uni.clearStorageSync();
								uni.reLaunch({
									url: '/pages/login/index2'
								});
							}
						}
					})

					// uni.showModal({
					// 	title: '请求失败',
					// 	content: res.data.alert_msg,
					// 	success: function(res) {
					// 		if (res.confirm) {
					// 			uni.reLaunch({
					// 				url: '/pages/login/login'
					// 			});
					// 			uni.clearStorageSync();
					// 		}
					// 	}
					// });
					// uni.reLaunch({
					// 	url: '/pages/login/index2'
					// });
					//uni.clearStorageSync();

				}

			},

			fail(err) {
				return uni.showToast({
					title: '请求失败了' + err,
					icon: 'none',
					duration: 5000
				})
				reject(err)
			},
			complete() {
				uni.hideLoading()

			}
		})
		// uni.request(httpDefaultOpts).then(
		// 	(res1) => {
		// 		const res = res1[1].data
		// 		if (res.meta.status == '000000') {
		// 			resolve(res)
		// 		} else {
		// 			uni.showToast({
		// 				title: '请求失败' + res.data.alert_msg,
		// 				icon: 'none',
		// 				duration: 5000
		// 			})
		// 			// uni.showModal({
		// 			// 	title: '请求失败',
		// 			// 	content: res.data.alert_msg,
		// 			// 	success: function(res) {
		// 			// 		if (res.confirm) {
		// 			// 			uni.reLaunch({
		// 			// 				url: '/pages/login/login'
		// 			// 			});
		// 			// 			uni.clearStorageSync();
		// 			// 		}
		// 			// 	}
		// 			// });
		// 			uni.reLaunch({
		// 				url: '/pages/login/index2'
		// 			});
		// 			//uni.clearStorageSync();

		// 		}
		// 	}
		// ).catch(
		// 	(response) => {
		// 		reject(response)
		// 	}
		// )
	})
	return promise
	//}
	// let token = uni.getStorageSync('token')
	//此token是登录成功后后台返回保存在storage中的

};

// 拦截器
const hadToken = (token) => {
	if (token == '' || token == undefined || token == null) {
		uni.showToast({
			title: '账号已过期，请重新登录',
			icon: 'none',
			complete: function() {
				uni.reLaunch({
					url: '/pages/login/index2'
				});
			}
		});
		return false;
	}
	return true
}


// 处理控制函数
const handleDeleteBlankParam = (newOptionsBody) => {
	const objectKeys = Object.keys(newOptionsBody);
	let paramInfo = {};


	let objValue = {};
	if (objectKeys && objectKeys.length > 0) {
		objectKeys.map(item => {


			if (typeof objValue === "function" || newOptionsBody[item] === "" || newOptionsBody[item] ===
				"null" || newOptionsBody[item] === null || newOptionsBody[item] === undefined ||
				newOptionsBody[item] === "undefined") {

			} else {
				objValue = newOptionsBody[item];


				// 判断是否是数组
				if (Array.isArray(objValue)) {

					const newList = [];

					if (objValue && objValue.length > 0) {
						objValue.map((info, index) => {

							if (Array.isArray(objValue[index])) {
								// 判断是否是数组

							}

							if (typeof objValue[index] === "number") {
								// 判断是否是数字

								newList.push(objValue)

							} else if (typeof objValue[index] === "string") {
								// 判断是否是都字符串

								newList.push(objValue[index])

							} else if (typeof objValue[index] === "object") {
								// 判断是否是都对象
								let newParamInfo = {};
								newParamInfo = handleDeleteBlankParam(objValue[index]);

								newList.push(newParamInfo)

							} else {
								newList.push(objValue[index])
							}

							return true;

						})
					}

					paramInfo = {
						...paramInfo,
						[item]: newList,
					}
				} else if (typeof objValue === "number") {
					// 判断是否是数字
					paramInfo = {
						...paramInfo,
						[item]: newOptionsBody[item],
					}

				} else if (typeof objValue === "string") {
					// 判断是否是都字符串
					paramInfo = {
						...paramInfo,
						[item]: newOptionsBody[item],
					}

				} else if (objValue instanceof Date) { //  moment.isMoment(objValue)
					// 判断当前对象是时间对象   objValue instanceof moment
					paramInfo = {
						...paramInfo,
						[item]: newOptionsBody[item],
					}

				} else if (typeof objValue === "object") {
					// 判断是否是都对象
					objValue = handleDeleteBlankParam(objValue);
					paramInfo = {
						...paramInfo,
						[item]: objValue,
					}

				} else {
					paramInfo = {
						...paramInfo,
						[item]: newOptionsBody[item],
					}
				}

			}
			return true;
		})
	}

	return paramInfo;

};

/**
 * 上传附件
 */
const uploadFilePromise = (url, filePath, formData) => {
	const phone = "mobile"
	const userInfo = uni.getStorageSync("userInfo")
	const company = uni.getStorageSync('companny')
	const comId = company ? company.split("@")[1] : "";
	let token = userInfo.token
	if (!opts.url.endsWith("login")) {
		const a = hadToken(token)
		if (!a) {
			return false
		}
	}
	return new Promise((resolve, reject) => {
		let a = uni.uploadFile({
			url: baseUrl + url, // 接口地址
			//files: file,
			filePath: filePath,
			name: 'file',
			header: {
				Authorization: token,
				'use-agent': phone,
			},
			formData: {
				...formData,
			},
			success: (retu) => {
				const res = retu.data ? JSON.parse(retu.data) : retu
				const temp = {
					...res,
					data: {
						alert_msg: res.data.alert_msg,
						list: res.data.list && res.data.list.length > 0 ? JSON.parse(
							aes.decrypt(res.data.list)) : res.data.list,
						pagination: res.data.pagination,
						total: res.data.total,
					}
				};
				if (temp.meta.status == '000000') {
					resolve(temp)
					console.log('uploadFilePromise', temp);
				} else {
					return uni.showToast({
						title: '请求失败了' + temp.data.alert_msg,
						icon: 'none',
						duration: 5000
					})
					reject(temp)
				}
			}
		});
	})
}


export default {
	baseUrl,
	httpRequest,
	httpTokenRequest,
	hadToken,
	handleDeleteBlankParam,
	uploadFilePromise,
}